package com.controller.front;

import cn.hutool.core.util.RandomUtil;
import com.entity.User;
import com.github.pagehelper.PageInfo;
import com.mapper.UserMapper;
import com.service.UserService;
import com.util.ValidatorUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("front")
public class UserFrontController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public String login(String email, String password, HttpServletResponse res, HttpSession session){
        Cookie c = new Cookie("name","啊嘞嘞");
        res.addCookie(c);
        User user = userService.selectUserByEmail(email);
        boolean login = userService.login(email, password);
        if(login){
            session.setAttribute("login",true);
            session.setAttribute("user",user);
            return "redirect:/front/main.do";
        }else{
            return "redirect:/front/login.jsp";
        }
    }
    @RequestMapping("/register")
    public String register(String email, String password,String password2, String nickname, String salt,Integer status, String code, Date create_date,String VCode,
                           Model model,HttpSession session){
        String realCode = (String) session.getAttribute("realCode");
        code = RandomUtil.randomString(6);
        if (VCode != null && !VCode.equalsIgnoreCase(realCode) && password != password2) {
            //如果验证码不正确，重定向到登录页面
            return "redirect:/front/login.jsp";
        }
        boolean register = userService.register(email, password,"abc",nickname, -1, code, new Date());
        if(register){
            model.addAttribute("email",email);
            return "redirect:/front/validateEmail.jsp";
        }else{
            return "redirect:/front/register.jsp";
        }
    }
    @RequestMapping("activeUser")
    public String validateEmail(String email,String code){
        boolean b = userService.activeUser(email, code);
        User user = userService.selectUserByEmail(email);
        if(b){
            user.setStatus(1);
            userService.updateUser(user);
            return "redirect:/front/registerOK.jsp";
        }else{
            return "redirect:/front/validateEmail.jsp";
        }
    }
}
